<?php

namespace app\purchase\logic;
use app\common\library\Excel;
use app\order\logic\OrderLogic;
use think\facade\Db;
use app\api\logic\ApiStockUpLogic;
class PlanSuggestLogic extends BasicLogic
{

    /**
     * @desc   备货建议seller_sku列表接口
     * @author luckyXiong
     * @date   2025-06-11
     */
    public function getSuggest($params=[]){
        $seller_sku         = getIsset($params,'seller_sku');
        $spu                = getIsset($params,'spu');
        $supply_id          = getIsset($params,'supply_id');
        $create_time        = getIsset($params,'create_time');
        $where              =  [];


        if($seller_sku){
            $where[] = ['seller_sku', 'like', '%' . $seller_sku . '%'];
        }

        $where[] = ['spu', '=',$spu];

        $where[] = ['suggest_sku_nums', '>',0];

        if (!empty($create_time)) {
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
        }

        if($supply_id){
            $where[] = ['supply_id', '=',$supply_id];
        }

        $field = 'spu,seller_sku,product_type,supply_name,suggest_sku_nums,color,size,cup';
        $list   = Db::name('purchase_suggest_plan')
            ->field($field)
            ->where($where)
            ->select()
            ->toArray();
        $current_info = current($list);


        //批量获取seller_sku
        $seller_skus= array_column($list,'seller_sku');
        $map   = [];
        $map[] = ['spu','=',$spu];
        $map[] = ['seller_sku','not in',$seller_skus];
        //未出现在要补货的spu里面的sku尺码获取
        $field = 'id,spu,seller_sku,color,size,cup';
        $other_size = Db::name('order_sku_size')->field($field)->where($map)->select()->toArray();
        $arr_size = [];
        if($other_size){
            foreach($other_size as $k=>$v){
                $arr_size[$k]['spu']              = $v['spu'];
                $arr_size[$k]['seller_sku']       = $v['seller_sku'];
                $arr_size[$k]['product_type']     = $current_info['product_type'];
                $arr_size[$k]['supply_name']      = $current_info['supply_name'];
                $arr_size[$k]['suggest_sku_nums'] = "";
                $arr_size[$k]['color']            = $v['color'];
                $arr_size[$k]['size']             = $v['size'];
                $arr_size[$k]['cup']              = $v['cup'];
            }
        }

        $cup = $current_info['cup']??"";

        //非罩杯的加尺码
        if($arr_size && empty($cup)){
            $list = array_merge($list,$arr_size);
        }


        if($cup){
            $list = self::sort_cup($list);
        }else{
            $list = self::sort_size($list);
        }



        //批量获取产品名称;
        $spus              = array_column($list,'spu');
        $spus              = array_values(array_unique($spus));
        $product_names     = Db::name('product')->field('id,spu,product_name')->whereIn('spu',$spus)->select()->toArray();
        $product_names_map = array_column($product_names,'product_name','spu');
        $price             = (new OrderLogic())->SpuProcurement($spu);
        $price             = getRes($price);
        foreach($list as $k=>$v){
            $list[$k]['product_name']      = $product_names_map[$v['spu']]??'';
            $list[$k]['single_price']      = $price;
            $list[$k]['arraive_time']      = '';
            $list[$k]['remark']            = '';
        }
        return  $this->jsonMessage(200,true,'获取成功',$list);
    }


    /**
     * @desc   备货建议seller_sku列表接口
     * @author luckyXiong
     * @date   2025-06-18
     */
    public function get_size($seller_sku,$product_type){
        //获取spu
        $spu_info    = explode('-', $seller_sku);
        $letter_arr  = ['A','B','C','D','E','F','G','H','I','J','K','L','M'];
        $cup         = '';
        $size        = '';
        $color       = $spu_info[1]??'';
        $spu_info_second = $spu_info[2]??'';
        if($product_type==1){
            //bra类型 拆分尺寸和罩杯;
            preg_match_all('/[0-9]+|[a-zA-Z]+/', $spu_info_second, $matches);
            $letter = $matches[0][1]??'';
            if(in_array($letter,$letter_arr)){
                $size = $matches[0][0]??'';
                $cup  = $letter;
            }else{
                $size = $spu_info_second;
                $cup  = '';
            }
        }else{
               $size = $spu_info_second;
        }
        return  [
            'color'=>$color,
            'size' =>$size,
            'cup'  =>$cup,
        ];

    }



    /**
     * @desc   备货建议spu列表接口
     * @author luckyXiong
     * @date   2025-06-12
     */
    public function getSpuSuggest($params=[]){
        $limit              = getIsset($params,'limit',20);
        $spu                = getIsset($params,'spu');
        $supply_id          = getIsset($params,'supply_id');
        $hot_type           = getIsset($params,'hot_type');
        $product_type       = getIsset($params,'product_type');
        $create_time        = getIsset($params,'create_time');
        $inventory_quantity = getIsset($params,'inventory_quantity');
        $on_way_quantity    = getIsset($params,'on_way_quantity');
        $not_send_quantity  = getIsset($params,'not_send_quantity');
        $produce_days       = getIsset($params,'produce_days');
        $sku_1days          = getIsset($params,'sku_1days');
        $suggest_sku_nums   = getIsset($params,'suggest_sku_nums');
        $where              = $order = [];

        if($hot_type){
            $where[] = ['hot_type', '=',$hot_type];
        }

        $where[] = ['suggest_sku_nums', '>',0];

        if (!empty($create_time)) {
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
        }

        if($spu){
            $spu     = explode(',',$spu);
            $where[] = ['spu', 'in',$spu];
        }


        if($product_type){
            $where[] = ['product_type', '=',$product_type];
        }

        if($supply_id){
            $where[] = ['supply_id', '=',$supply_id];
        }

        if($inventory_quantity){
            $order['inventory_quantity'] = $inventory_quantity;
        }

        if($on_way_quantity){
            $order['on_way_quantity'] = $on_way_quantity;
        }

        if($on_way_quantity){
            $order['on_way_quantity'] = $on_way_quantity;
        }


        if($produce_days){
            $order['produce_days'] = $produce_days;
        }

        if($sku_1days){
            $order['sku_1days'] = $sku_1days;
        }

        if($not_send_quantity){
            $order['not_send_quantity'] = $not_send_quantity;
        }

        if($suggest_sku_nums){
            $order['suggest_sku_nums'] = $suggest_sku_nums;
        }


        if(!$inventory_quantity && !$on_way_quantity &&!$not_send_quantity &&!$sku_1days && !$suggest_sku_nums){
               $order['suggest_sku_nums'] = 'desc';
        }

        $field = 'id,spu,hot_type,product_type,suggest_days,image_url,supply_name,supply_id,create_time,
                 sum(inventory_quantity) as inventory_quantity,sum(on_way_quantity) as on_way_quantity,
                 sum(on_way_quantity) as on_way_quantity,sum(produce_days) as produce_days,suggest_rate,
                 sum(sku_1days) as sku_1days,sum(suggest_sku_nums) as suggest_sku_nums,sum(sku_3days) as sku_3days,
                 sum(sku_7days) as sku_7days,sum(not_send_quantity) as not_send_quantity,count(seller_sku) as sku_nums,sum(sku_15days) as sku_15days,sum(sku_30days) as sku_30days';

        $res   = Db::name('purchase_suggest_plan')
            ->field($field)
            ->where($where)
            ->group('spu')
            ->order($order)
            ->paginate($limit);
        $list = $res->items()?:[];
        $spus = array_column($list,'spu');
        $field    = 'spu,supply_name,all_inventory_quantity,on_way_quantity, not_send_quantity,sku_1days';
        $all_list = Db::name('purchase_suggest_plan_spu')->field($field)->whereIn('spu',$spus)->select()->toArray();
        $all_list_map = array_column($all_list,null,'spu');
        foreach($list as $k=>$v){
            $all_info                       = $all_list_map[$v['spu']]??[];
            $list[$k]['produce_days']       = $v['produce_days']/$v['sku_nums'];
            $list[$k]['safe_quantity']      = ceil($v['sku_1days']*$v['suggest_days']);
            $list[$k]['inventory_quantity'] = $all_info['all_inventory_quantity']??0;
            $list[$k]['on_way_quantity']    = $all_info['on_way_quantity']??0;
            $list[$k]['not_send_quantity']  = $all_info['not_send_quantity']??0;
            $sku_1days                      = $all_info['sku_1days']??0;
            $list[$k]['sku_1days']          = $sku_1days;
            $list[$k]['safe_quantity']      = $sku_1days*7;
            $list[$k]['supply_name']        = $all_info['supply_name']??'';
        }

        $data = [
            'list'   => $list,
            'total'  => $res->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }


    public function get_days7_sku($spus){
        $where     = [];
        $yesterday = strtotime(date('Y-m-d', time() - timezone()));
        $yesterdayEnd = strtotime(date('Y-m-d', strtotime('-6 day') - timezone()));
        $where[] = ['createtime', '<=', $yesterday];
        $where[] = ['createtime', '>=', $yesterdayEnd];
        $where[] = ['is_seel', '=', 0];
        $where[] = ['spu', 'in', $spus];
        $field      = 'sum(realcount) AS skuquantity,spu';
        $nums_info  = Db::name('order_skuinfo')->where($where)->field($field)->select()->toArray();
        return $nums_info;
    }






    /**
     * @desc   罩杯类型排序
     * @author luckyXiong
     * @date   2025-06-19
     */
    public function sort_cup($list){
        $sizeOrder = ['30', '32', '34', '36', '38', '40', '42', '44', '46', '48', '50', '52', '54', '56'];
        $cupOrder  = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'];
        usort($list, function ($a, $b) use ($sizeOrder, $cupOrder) {
            // 比较 size
            $sizeA = array_search($a['size'], $sizeOrder);
            $sizeB = array_search($b['size'], $sizeOrder);

            if ($sizeA !== $sizeB) {
                return $sizeA - $sizeB;
            }

            // 如果 size 相同，比较 cup
            $cupA = array_search($a['cup'], $cupOrder);
            $cupB = array_search($b['cup'], $cupOrder);

            return $cupA - $cupB;
        });
        return $list;
    }


    /**
     * @desc   非罩杯类型排序
     * @author luckyXiong
     * @date   2025-06-19
     */
    public function sort_size($list){
        $sizeOrder = [
            'XS','S','XS/S','S/M','M','M/L', 'L', 'L/XL', 'XL',
            'XL/2XL', '2XL', '3XL', '3XL/4XL', '4XL','4XL/5XL', '5XL', '6XL','7XL'
        ];
        usort($list, function($a, $b) use ($sizeOrder) {
            return array_search($a['size'], $sizeOrder) - array_search($b['size'], $sizeOrder);
        });
        return $list;
    }






    /**
     * @desc   编辑备货建议列表接口
     * @author luckyXiong
     * @date   2025-06-10
     */
    public function editSuggest($params=[]){
        $id                  = $params['id']??'';
        $hot_type            = $params['hot_type']??'';
        $suggest_days        = $params['suggest_days']??'';
        $inventory_quantity  = $params['inventory_quantity']??'';
        $available_quantity  = $params['available_quantity']??'';
        $on_way_quantity     = $params['on_way_quantity']??'';
        $safe_quantity       = $params['safe_quantity']??'';
        $not_send_quantity   = $params['not_send_quantity']??'';
        $produce_days        = $params['produce_days']??'';
        $track_days          = $params['track_days']??'';
        $suggest_sku_nums    = $params['suggest_sku_nums']??'';


        $update_data = [
            'hot_type'            => $hot_type,
            'suggest_days'        => $suggest_days,
            'inventory_quantity'  => $inventory_quantity,
            'available_quantity'  => $available_quantity,
            'on_way_quantity'     => $on_way_quantity,
            'safe_quantity'       => $safe_quantity,
            'not_send_quantity'   => $not_send_quantity,
            'produce_days'        => $produce_days,
            'track_days'          => $track_days,
            'suggest_sku_nums'    => $suggest_sku_nums,
            'update_time'         => date("Y-m-d H:i:s", time()),
        ];
        //数据更新入库;
        Db::name('purchase_suggest_plan')->where(['id'=>$id])->update($update_data);
        return  $this->jsonMessage(200,true,'编辑成功',null);
    }


    /**
     * @desc   删除接口
     * @author luckyXiong
     * @date   2025-06-10
     */
    public function deleteSuggest($params=[]){
        $id   = $params['id']??'';
        Db::name('purchase_suggest_plan')->where(['id'=>$id])->delete();
        return  $this->jsonMessage(200,true,'操作成功',null);
    }

    /**
     * @desc   添加备注接口
     * @author luckyXiong
     * @date   2025-06-10
     */
    public function addRemark($params=[]){
        $id           = $params['id']??'';
        $remark       = $params['remark']??'';
        $remark_color = $params['remark_color']??'';
        Db::name('purchase_suggest_plan')->where(['id'=>$id])->update(
            [
                'remark'       =>$remark,
                'remark_color' =>$remark_color,
                'update_time'  =>date("Y-m-d H:i:s", time()),
            ]
        );
        return  $this->jsonMessage(200,true,'操作成功','');
    }


    


    /**
     * @desc   单独更新建议备货量
     * @author luckyXiong
     * @date   2025-06-10
     */
    public function editSuggestSkuNums($params=[]){
        $id                  = $params['id']??'';
        $produce_days        = $params['produce_days']??'';
        $spu                 = $params['spu']??'';
        $field               = 'id,spu,seller_sku,sku_1days,track_days,suggest_days,not_send_quantity,on_way_quantity,inventory_quantity';
        $list                = Db::name('purchase_suggest_plan')->field($field)->where('spu',$spu)->select()->toArray();
        foreach($list as $v){
               self::change_suggest_plan($v,$produce_days);
        }
        //同时存储货期,下次使用;
        $exist_info = Db::name('purchase_suggest_plan_produce')->where('spu',$spu)->find();
        if(!$exist_info){
             $temp = [
                 'spu'         =>$spu,
                 'produce_days'=>$produce_days,
                 'create_time'  =>date("Y-m-d H:i:s", time()),
             ];
            Db::name('purchase_suggest_plan_produce')->insert($temp);
        }else{
            Db::name('purchase_suggest_plan_produce')->where('spu',$spu)->update(
                [
                    'produce_days'=>$produce_days,
                    'create_time'  =>date("Y-m-d H:i:s", time()),
                ]
            );
        }
        return  $this->jsonMessage(200,true,'编辑成功',null);
    }


    /**
     * @desc   单独更新备货幅度
     * @author luckyXiong
     * @date   2025-07-01
     */
    public function editSuggestRate($params=[]){
        $suggest_rate        = $params['suggest_rate']??'';
        $spu                 = $params['spu']??'';
        $field               = 'id,spu,seller_sku,sku_1days,produce_days,track_days,suggest_days,not_send_quantity,on_way_quantity,inventory_quantity';
        $list                = Db::name('purchase_suggest_plan')->field($field)->where('spu',$spu)->select()->toArray();
        foreach($list as $v){
            self::change_suggest_rate($v,$suggest_rate);
        }
        //同时存储货期,下次使用;
        $exist_info = Db::name('purchase_suggest_plan_produce')->where('spu',$spu)->find();
        if(!$exist_info){
            $temp = [
                'spu'         =>$spu,
                'suggest_rate'=>$suggest_rate,
                'create_time'  =>date("Y-m-d H:i:s", time()),
            ];
            Db::name('purchase_suggest_plan_produce')->insert($temp);
        }else{
            Db::name('purchase_suggest_plan_produce')->where('spu',$spu)->update(
                [
                    'suggest_rate'=>$suggest_rate,
                    'create_time'  =>date("Y-m-d H:i:s", time()),
                ]
            );
        }
        return  $this->jsonMessage(200,true,'编辑成功',null);
    }


    /**
     * @desc   更新备货建议数量
     * @author luckyXiong
     * @date   2025-06-17
     */
    private function change_suggest_plan($info,$produce_days){
        //日均销量;
        $day_sale             = $info['sku_1days'];
        $suggest_sku_nums     = $day_sale*($produce_days + $info['track_days'] +$info['suggest_days']) +  $info['not_send_quantity'] - ($info['on_way_quantity']+$info['inventory_quantity']);
        $suggest_sku_nums     = ceil($suggest_sku_nums);
        Db::name('purchase_suggest_plan')->where('seller_sku',$info['seller_sku'])->update([
            'suggest_sku_nums'=> $suggest_sku_nums,
            'produce_days'    => $produce_days,
            'create_time'     => date("Y-m-d H:i:s", time()),
        ]);
    }


    /**
     * @desc   更新备货幅度数量
     * @author luckyXiong
     * @date   2025-06-30
     */
    private function change_suggest_rate($info,$suggest_rate){
        //日均销量;
        $day_sale             = $info['sku_1days'];
        $pre_suggest_sku_nums = $day_sale*($info['produce_days'] + $info['track_days'] +$info['suggest_days'])*$suggest_rate;
        $suggest_sku_nums     = $pre_suggest_sku_nums +  $info['not_send_quantity'] - ($info['on_way_quantity']+$info['inventory_quantity']);
        $suggest_sku_nums     = ceil($suggest_sku_nums);
        Db::name('purchase_suggest_plan')->where('seller_sku',$info['seller_sku'])->update([
            'suggest_sku_nums'=> $suggest_sku_nums,
            'suggest_rate'    => $suggest_rate,
            'create_time'     => date("Y-m-d H:i:s", time()),
        ]);
    }







    /**
     * @desc   导出备货建议
     * @author luckyXiong
     * @date   2025-06-11
     */
    public function export($params){
        $spu                = getIsset($params,'spu');
        $supply_id          = getIsset($params,'supply_id');
        $hot_type           = getIsset($params,'hot_type');
        $product_type       = getIsset($params,'product_type');
        $create_time        = getIsset($params,'create_time');
        $where              = $order = [];

        if($hot_type){
            $where[] = ['hot_type', '=',$hot_type];
        }

        if($spu){
            $spu     = explode(',',$spu);
            $where[] = ['spu', 'in',$spu];
        }


        $where[] = ['status', '=',1];

        if (!empty($create_time)) {
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
        }


        if($product_type){
            $where[] = ['product_type', '=',$product_type];
        }

        if($supply_id){
            $where[] = ['supply_id', '=',$supply_id];
        }

        $order['create_time'] = 'desc';

        $field = '*';
        $list   = Db::name('purchase_suggest_plan')
            ->field($field)
            ->where($where)
            ->order($order)
            ->select()
            ->toArray();

        $product_arr = [
            '1'=>'bra类型',
            '2'=>'shapewear类型',
            '3'=>'swim类型',
            '4'=>'panties类型',
            '5'=>'其他',
        ];

        $hot_arr = [
            '1'=>'热销',
            '2'=>'潜力款',
            '3'=>'新品',
            '4'=>'中长尾款',
        ];

        foreach($list as $k=>$v){
            $list[$k]['days_sale']    = $v['sku_3days'].'/'.$v['sku_7days'].'/'.$v['sku_15days'].'/'.$v['sku_30days'];
            $list[$k]['product_type'] = $product_arr[$v['product_type']]??'';
            $list[$k]['hot_type']     = $hot_arr[$v['hot_type']]??'';

        }

        $header[] = ['spu', 'spu'];
        $header[] = ['商品sku', 'seller_sku'];
        $header[] = ['产品类型', 'product_type'];
        $header[] = ['热销类型', 'hot_type'];
        $header[] = ['库存数量', 'inventory_quantity'];
        $header[] = ['在途数量', 'on_way_quantity'];
        $header[] = ['未发订单数量', 'not_send_quantity'];
        $header[] = ['货期', 'produce_days'];
        $header[] = ['安全数量', 'remark'];
        $header[] = ['备货天数', 'remark'];
        $header[] = ['3/7/15/30', 'days_sale'];
        $header[] = ['建议备货数量', 'suggest_sku_nums'];
        $header[] = ['供应商', 'supply_name'];
        $header[] = ['创建时间', 'create_time'];
        $fileName = "suggest_spu_nums";
        Excel::exportData($list, $header, $fileName, 'xlsx');
        return  $this->jsonMessage(200,true,'导出成功',null);
    }


    /**
     * @desc   导出备货建议明细
     * @author luckyXiong
     * @date   2025-06-11
     */
    public function exportSku($params){
        $spu                = getIsset($params,'spu');
        $hot_type           = getIsset($params,'hot_type');
        $product_type       = getIsset($params,'product_type');
        $create_time        = getIsset($params,'create_time');
        $where              = $order = [];

        if($hot_type){
            $where[] = ['hot_type', '=',$hot_type];
        }

        $where[] = ['spu', '=',$spu];

        $where[] = ['status', '=',1];

        if (!empty($create_time)) {
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
        }


        if($product_type){
            $where[] = ['product_type', '=',$product_type];
        }

        $product_arr = [
            '1'=>'bra类型',
            '2'=>'shapewear类型',
            '3'=>'swim类型',
            '4'=>'panties类型',
            '5'=>'其他',
        ];

        $hot_arr = [
            '1'=>'热销',
            '2'=>'潜力款',
            '3'=>'新品',
            '4'=>'中长尾款',
        ];

        $order['create_time'] = 'desc';

        $field = '*';
        $list   = Db::name('purchase_suggest_plan')
            ->field($field)
            ->where($where)
            ->order($order)
            ->select()
            ->toArray();

        foreach($list as $k=>$v){
            $list[$k]['days_sale'] = $v['sku_3days'].'/'.$v['sku_7days'].'/'.$v['sku_15days'].'/'.$v['sku_30days'];
        }

        foreach($list as $k=>$v){
            $list[$k]['days_sale']    = $v['sku_3days'].'/'.$v['sku_7days'].'/'.$v['sku_15days'].'/'.$v['sku_30days'];
            $list[$k]['product_type'] = $product_arr[$v['product_type']]??'';
            $list[$k]['hot_type']     = $hot_arr[$v['hot_type']]??'';
        }

        $header[] = ['spu', 'spu'];
        $header[] = ['商品sku', 'seller_sku'];
        $header[] = ['产品类型', 'product_type'];
        $header[] = ['热销类型', 'hot_type'];
        $header[] = ['库存数量', 'inventory_quantity'];
        $header[] = ['在途数量', 'on_way_quantity'];
        $header[] = ['未发订单数量', 'not_send_quantity'];
        $header[] = ['货期', 'produce_days'];
        $header[] = ['安全数量', 'remark'];
        $header[] = ['备货天数', 'remark'];
        $header[] = ['3/7/15/30', 'days_sale'];
        $header[] = ['建议备货数量', 'suggest_sku_nums'];
        $header[] = ['供应商', 'supply_name'];
        $header[] = ['备注', 'remark'];
        $header[] = ['创建时间', 'create_time'];
        $fileName = "suggest_sku_nums";
        Excel::exportData($list, $header, $fileName, 'xlsx');
        return  $this->jsonMessage(200,true,'导出成功',null);
    }


    /**
     * @desc   获取采购合同数据明细
     * @author luckyXiong
     * @date   2025-06-16
     */
    public function get_contact_list($params=[]){
        $spu  = $params['spu']??'';
        Db::name('purchase_suggest_plan')->where('spu',$spu)->update([
            'place_status'    => 2,
            'create_time'     => date("Y-m-d H:i:s", time()),
        ]);
        return  $this->jsonMessage(200,true,'操作成功',null);
    }


    /**
     * @desc  确认合同通过
     * @author luckyXiong
     * @date   2025-06-16
     */
    public function check_contract($params=[]){
        $sku_list = $params['sku_list']??'';
        $spu      = $params['spu']??'';
        htmlLog(['sku_list'=>$sku_list],OPERATE_LOG . date('Ym') . '/check_contract/' . date('Ymd') . '.txt');
        $arr      = [];
        //获取批次号;
        $admin_id     = $params['admin_id']??'';
        $batch_id     = self::get_batch_id($admin_id);
        $create_operator = Db::name('system_admin')->where(['id'=>$admin_id])->value('username');
        $exist_info = Db::name('product_contract')->where(['batch_id'=>$batch_id])->find();
        if($exist_info){
            $batch_id = self::get_batch_id($admin_id);
        }

        $exist_info = Db::name('purchase_suggest_plan')->where(['spu'=>$spu])->find();
        foreach($sku_list as $v){
            $temp = [
                'spu'                =>$v['spu']??'',
                'seller_sku'         =>$v['seller_sku']??'',
                'batch_id'           =>$batch_id,
                'suggest_days'       =>$exist_info['suggest_days']??'',
                'inventory_quantity' =>$exist_info['inventory_quantity']??'',
                'available_quantity' =>$exist_info['available_quantity']??'',
                'on_way_quantity'    =>$exist_info['on_way_quantity']??'',
                'safe_quantity'      =>$exist_info['safe_quantity']??'',
                'not_send_quantity'  =>$exist_info['not_send_quantity']??'',
                'produce_days'       =>$exist_info['produce_days']??'',
                'track_days'         =>$exist_info['track_days']??'',
                'suggest_sku_nums'   =>$v['suggest_sku_nums']??'',
                'single_price'       =>$v['single_price']??'',
                'contract_status'    =>2,
                'color'              =>$v['color']??'',
                'size'               =>$v['size']??'',
                'cup'                =>$v['cup']??'',
                'product_type'       =>$exist_info['product_type']??'5',
                'image_url'          =>$exist_info['image_url']??'',
                'operate_id'         =>$admin_id,
                'supply_id'          =>$exist_info['supply_id']??'',
                'supply_name'        =>$exist_info['supply_name']??'',
                'create_time'        =>date("Y-m-d H:i:s", time()),
            ];
            $arr[] = $temp;
        }
        $curren_info = current($arr);
        //数据入库;
        try{
            Db::name('product_contract')->insert(
                [
                    'batch_id'       =>$batch_id,
                    'spu'            =>$spu,
                    'operate_id'     =>$admin_id,
                    'create_operator'=>$create_operator,
                    'supply_id'      =>$curren_info['supply_id']??'',
                    'supply_name'    =>$curren_info['supply_name']??'',
                    'image_url'      =>$curren_info['image_url']??'',
                    'create_time'    =>date("Y-m-d H:i:s",time()),
                ]
            );
            Db::name('purchase_suggest_water')->insertAll($arr);
            $this->jsonMessage(200, true,'操作成功',null);
        }catch (Exception $e){
            Db::rollback(); // 回滚事务
            $this->jsonMessage(201,false,$e->getMessage(),null);
        }
    }


    /**
     * @desc  导出明细
     * @author luckyXiong
     * @date   2025-06-25
     */
    public function export_detail($params=[]){
        $spu                = getIsset($params,'spu');
        $where              = [];
        $where[]            = ['spu', '=',$spu];
        $where[]            = ['suggest_sku_nums', '>',0];
        $field  = '*';
        $list   = Db::name('purchase_suggest_plan')
            ->field($field)
            ->where($where)
            ->select()
            ->toArray();

        $header[] = ['spu', 'spu'];
        $header[] = ['商品sku', 'seller_sku'];
        $header[] = ['产品颜色', 'color'];
        $header[] = ['产品尺码', 'size'];
        $header[] = ['产品罩杯', 'cup'];
        $header[] = ['日均销量', 'sku_1days'];
        $header[] = ['货期', 'produce_days'];
        $header[] = ['物流时间', 'track_days'];
        $header[] = ['备货天数', 'suggest_days'];
        $header[] = ['未发订单数量', 'not_send_quantity'];
        $header[] = ['采购在途数量', 'on_way_quantity'];
        $header[] = ['库存数量', 'inventory_quantity'];
        $header[] = ['建议备货数量', 'suggest_sku_nums'];
        $header[] = ['创建时间', 'create_time'];
        $fileName = "export_detail_sku_nums";
        Excel::exportData($list, $header, $fileName, 'xlsx');
        return  $this->jsonMessage(200,true,'导出成功',null);
    }




    /**
     * @desc   获取批次号列表
     * @author luckyXiong
     * @date   2024-10-28
     */
    private function get_batch_id($admin_id=''){
        $currentMonth = date('m');
        $currentYear  = date('Y');
        $currentday   = date('d');
        if(strlen($admin_id) > 2){
            $admin_id = substr($admin_id, 0, 2);
        }
        return $currentYear.$currentMonth.$currentday.$admin_id.random_int(100, 999);
    }


}